﻿#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

using std::cin;
using std::cout;
using std::endl;
using std::string;
#define BUF_SIZE 1024
#define SERVER_IP "127.0.0.1"
#define PORT 9999
void Error(const string &msg)
{
  cout << msg << endl;
  exit(-1);
}
int main()
{
  // step01:创建udp客户端套接字
  int sock_clnt;
  if ((sock_clnt = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    Error("socket() error!");
  cout << "socket() ok ..." << endl;
  sockaddr_in addr_serv{};
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.s_addr = inet_addr(SERVER_IP);
  addr_serv.sin_port = htons(PORT);
  // step02:传输数据
  char msg[BUF_SIZE];
  sockaddr_in addr_from{};
  socklen_t size_addr_from = sizeof(addr_from);
  char response[BUF_SIZE];
  int size_addr_serv = 0;
  while (1)
  {
    cout << "Please input msg(Q or q to quit): ";
    cin >> msg;
    if (!strcmp(msg, "Q") || !strcmp(msg, "q"))
      break;
    sendto(sock_clnt, msg, BUF_SIZE, 0, (sockaddr *)&addr_serv, sizeof(addr_serv));
    recvfrom(sock_clnt, response, sizeof(response), 0, (sockaddr *)&addr_from, &size_addr_from);
    cout << "Response message from server:{" << response << "}" << endl;
    cout << addr_from.sin_addr.s_addr << "..." << addr_from.sin_port << endl;
    cout << addr_serv.sin_addr.s_addr << "..." << addr_serv.sin_port << endl;
  }
  close(sock_clnt);
  return 0;
}
